<!--
 * @Description: 留言板
 * @Author: zheng yiliang
 * @Date: 2021-05-27 17:32:40
 * @LastEditTime: 2021-06-11 10:15:28
 * @LastEditors: zheng yiliang
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="状态" prop="is_handle">
        <el-select
          size="mini"
          v-model="queryParams.is_handle"
          placeholder="请选择"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="已读" :value="1"></el-option>
          <el-option label="未读" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row type="flex">
      <el-col></el-col>
      <el-col class="tr">
        <right-toolbar
          :show-search.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-col>
    </el-row>

    <el-table class="mgt10" v-loading="loading" :data="messages">
      <el-table-column type="index" width="50" label="#"></el-table-column>

      <el-table-column type="expand">
        <template #default="{ row }">
          <template v-if="!row.reply.length">暂无回复...</template>
          <template v-else>
            <ul class="blog-comment" id="blog-comment">
              <li
                v-for="(reply, i) in row.reply"
                :key="i"
                class="comment-child"
              >
                <el-avatar
                  style="position: absolute"
                  class="header-img"
                  :size="40"
                  :src="reply.fromAvatar"
                ></el-avatar>
                <div class="info">
                  <span class="username">{{ reply.from }}</span>
                  <span class="blogger" v-if="reply.fromType === 0">站长</span>
                  <span style="padding-right: 5px">回复</span>
                  <span class="username">{{ reply.to }}</span>
                  <span>{{ reply.comment }}</span>
                </div>
                <p class="info">
                  <span class="comment-time">{{
                    reply.create_time | dateFormate
                  }}</span>
                  <el-button
                    type="text"
                    v-if="_inputChildShow(reply)"
                    class="btn-reply"
                    @click="hideReplyInput(reply, row)"
                    >收起</el-button
                  ><el-button
                    type="text"
                    v-else
                    class="btn-reply"
                    @click="showReplyInput(reply, row)"
                    >回复</el-button
                  >
                  <el-button
                    v-if="reply.is_handle !== 2"
                    type="text"
                    class="btn-reply"
                    >已读</el-button
                  >
                  <el-button
                    style="color: #f56c6c"
                    class="btn-reply"
                    v-else
                    type="text"
                    @click="handleReplyRead(reply, row._id)"
                    >标记为已读</el-button
                  >
                  <el-button
                    type="text"
                    class="btn-reply"
                    @click="delReplyMsg(reply._id, row._id, row)"
                    >删除</el-button
                  >
                </p>
                <div class="replycontainer" v-show="_inputChildShow(reply)">
                  <el-form>
                    <el-form-item>
                      <el-input
                        v-model="replyComment"
                        :rows="3"
                        type="textarea"
                        :placeholder="`回复${reply.from}：${reply.comment}`"
                      ></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button
                        @click="sendCommentReply(reply, row)"
                        type="primary"
                        class="layui-btn layui-btn-xs"
                      >
                        提交
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </li>
            </ul>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="留言人"
        width="160"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="头像" class-name="avatar-reply">
        <template #default="{ row }">
          <el-badge value="new" v-if="row.is_handle === 2">
            <img :src="row.headImg" />
          </el-badge>
          <img :src="row.headImg" v-else />
        </template>
      </el-table-column>

      <el-table-column
        prop="comment"
        width="280"
        label="留言内容"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="总回复数">
        <template #default="{ row }">
          <span class="noreadreply" style="background: #00b672">
            {{ row.reply.length }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="未读回复" width="120">
        <template #default="{ row }">
          <span
            class="noreadreply"
            :style="{
              backgroundColor: !replyCount(row.reply) ? '#00b672' : '#f56c6c'
            }"
          >
            {{ replyCount(row.reply) }}
          </span>
          <el-button
            v-if="replyCount(row.reply)"
            @click="allRed(row)"
            style="margin-left: 10px; color: #f56c6c"
            size="mini"
            type="text"
            >一键已读</el-button
          >
        </template>
      </el-table-column>
      <el-table-column width="160" label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.time | formatDate }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="260"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.is_handle === 2"
            style="color: #f56c6c"
            @click="handleRead(scope.row)"
            >标记为已读</el-button
          >
          <el-button v-else size="mini" type="text" icon="el-icon-edit"
            >已读</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-checked"
            @click="replyFirst(scope.row)"
            >回复</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="提示" :visible.sync="replyDialog">
      <el-input
        v-model="replyComment"
        :rows="3"
        type="textarea"
        :placeholder="`回复${firstComment.name}：${firstComment.comment}`"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="replyDialog = false">取 消</el-button>
        <el-button type="primary" @click="sendCommentReply(firstComment)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分页区域 -->
    <el-pagination
      background
      :current-page="queryParams.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryParams.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script>
import {
  allMsg,
  delMessage,
  delReplyMessage,
  replyMessage,
  replyRead,
  read,
  allRead
} from '@/api/message'
import RightToolbar from '@/components/RightToolbar'
import { mapGetters } from 'vuex'

export default {
  name: 'Menu',
  components: { RightToolbar },
  data() {
    return {
      firstComment: '',
      replyComment: '',
      total: 0,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      replyDialog: false,
      messages: [],
      // 查询参数
      queryParams: {
        is_handle: '',
        pagenum: 1,
        pagesize: 10
      }
    }
  },
  computed: {
    ...mapGetters(['name', 'avatar'])
  },
  created() {
    this.getList()
  },
  filters: {
    dateFormate(date) {
      // 获取js 时间戳
      date = new Date(date).getTime()
      let time = new Date().getTime()
      // 去掉 js 时间戳后三位，与php 时间戳保持一致
      time = parseInt((time - date) / 1000)
      // 存储转换值
      let s
      if (time < 60 * 10) {
        // 十分钟内
        return '刚刚'
      } else if (time < 60 * 60 && time >= 60 * 10) {
        // 超过十分钟少于1小时
        s = Math.floor(time / 60)
        return s + '分钟前'
      } else if (time < 60 * 60 * 24 && time >= 60 * 60) {
        // 超过1小时少于24小时
        s = Math.floor(time / 60 / 60)
        return s + '小时前'
      } else if (time < 60 * 60 * 24 * 30 && time >= 60 * 60 * 24) {
        // 超过1天少于30天内
        s = Math.floor(time / 60 / 60 / 24)
        return s + '天前'
      } else {
        // 超过30天ddd
        date = new Date(parseInt(date))
        return (
          date.getFullYear() +
          '/' +
          (date.getMonth() + 1) +
          '/' +
          date.getDate()
        )
      }
    }
  },
  methods: {
    async allRed(row) {
      const { _RejCode } = await allRead({ _id: row._id })
      if (_RejCode !== '00000000') return
      row.reply.forEach((item) => (item.is_handle = 1))
    },
    async handleRead(row) {
      const { _RejCode } = await read({ _id: row._id })
      if (_RejCode !== '00000000') return
      row.is_handle = 1
    },
    async handleReplyRead(reply, _id) {
      const { _RejCode } = await replyRead({ replyId: reply._id, _id })
      if (_RejCode !== '00000000') return
      reply.is_handle = 1
    },
    replyCount(arr) {
      return arr.filter((item) => item.is_handle === 2).length
    },
    showReplyInput(reply, row) {
      console.log(reply, row)
      this.replyComment = ''
      row.reply.forEach((item) => {
        item.inputShow = false
      })
      reply.inputShow = true
    },
    hideReplyInput(reply, row) {
      this.replyComment = ''
      row.reply.forEach((item) => {
        item.inputShow = false
      })
    },
    _inputChildShow(reply) {
      return reply.inputShow
    },
    delReplyMsg(replyId, id, row) {
      this.$confirm('是否确认删除此留言?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          return delReplyMessage({ replyId, _id: id })
        })
        .then((res) => {
          row.reply = row.reply.filter((item) => item._id !== replyId)
          this.$message.success(res._RejMsg)
        })
    },
    replyFirst(item) {
      this.replyDialog = true
      this.firstComment = item
    },
    async sendCommentReply(replys, item) {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '评论不能为空'
        })
        return
      }
      console.log(replys)
      const reply = {
        from: this.name,
        fromAvatar: this.avatar,
        to: replys.name || replys.from,
        toId: replys.id || replys.fromId,
        toAvatar: replys.headImg || replys.fromAvatar,
        comment: this.replyComment,
        _id: item ? item._id : replys._id
      }
      const { _RejCode, data, _RejMsg } = await replyMessage(reply)
      if (_RejCode !== '00000000') {
        this.$message({
          showClose: true,
          type: 'error',
          message: _RejMsg
        })
        return
      }
      this.replyDialog = false
      this.replyComment = ''
      this.getList()

      console.log(data)
    },
    async getList() {
      this.loading = true
      const { _RejCode, data } = await allMsg(this.queryParams).catch(
        (err) => err
      )
      if (_RejCode !== '00000000') {
        this.total = 0
        this.messages = []
        this.loading = false
        return
      }
      this.messages = data.messages
      this.total = data.count
      this.loading = false
    },
    // 一页显示多少条数据
    handleSizeChange(pageSize) {
      this.queryParams.pagesize = pageSize
      this.queryParams.pagenum = 1
      this.getList()
    },
    // 当前页数，当前在第几页
    handleCurrentChange(curPage) {
      this.queryParams.pagenum = curPage
      this.getList()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pagenum = 1
      this.queryParams.pagesize = 10
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.$refs['queryForm'].resetFields()
      this.queryParams.is_handle = ''
      this.handleQuery()
    },

    // /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除留言人为"' + row.name + '"的留言?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          return delMessage({ id: row._id })
        })
        .then((res) => {
          this.getList()
          this.$message.success(res._RejMsg)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .avatar-reply {
  .cell {
    overflow: initial !important;
  }
  .el-badge__content {
    line-height: 15px;
  }
}
.noreadreply {
  // background-color: #;
  border-radius: 10px;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  text-align: center;
  white-space: nowrap;
  border: 1px solid #fff;
}
.blog-comment {
  margin: 0px;
  // padding-left: 0px;
  .el-button {
    padding-top: 5px;
    padding-bottom: 5px;
  }
  li {
    list-style: none;
    padding: 15px 0 10px 0;
    border-bottom: 1px dotted #bbb;
    &:last-child {
      border-bottom: 0px;
    }
  }
  .blogger {
    display: inline-block;
    padding: 2px 5px;
    margin: 0px 5px;
    color: #fff;
    background: #6bc30d;
    border-radius: 3px;
    line-height: 16px;
    font-size: 12px !important;
  }
  .line-hr {
    border-top: 1px dotted #bbb;
    height: 1px;
    margin: 10px 0;
    margin-left: 53px;
  }
  .el-avatar {
    img {
      width: 40px !important;
      height: 100% !important;
    }
  }

  .el-form-item {
    margin-bottom: 2px;
  }
  .btn-reply {
    padding: 0px;
    font-size: 13px;
  }
  .blog-editor {
    .el-form-item {
      margin-top: 16px;
    }
  }
  .comment-content,
  .info,
  .replycontainer {
    margin-left: 53px;
  }
  .info-footer {
    font-size: 13px;
  }

  .blog-comment .info span {
    padding-right: 5px;
  }

  .info .username {
    color: #01aaed;
    margin-right: 5px;
  }
  .info .btn-reply {
    color: #009688;
    margin-left: 10px;
  }
  .comment-content {
    padding: 2px 0 5px 0;
    min-height: 30px;
    font-size: 13px;
    word-break: break-all;
  }

  .comment-parent > img {
    width: 45px;
    height: 45px;
    margin: 5px 5px 5px 0;
    position: absolute;
    border-radius: 50px;
  }
  .comment-child > img {
    width: 40px;
    height: 40px;
    margin: 5px 5px 5px 0;
    position: absolute;
    border-radius: 50px;
  }
  .comment-child {
    min-height: 50px;
  }
  .comment-child .info {
    margin-left: 48px;
    font-size: 12px;
    line-height: 20px;
  }
}
</style>
